# coding:utf-8

import math
import types

from result import g_ret
from copy import deepcopy
import settings


def pagequery(mongo, table, query={}, sort=None, pagesize=500, page=1):
    """
    分页查询
    :param mongo:  数据库实例
    :param table:  表名
    :param query:  查询条件
    :param sort:   排序条件
    :param pagesize: 每页条数
    :param page:    页码
    :return: 
    """
    try:
        pagesize = int(pagesize)
        page = int(page)
    except Exception as e:
        print(e)
    ret = deepcopy(g_ret)
    pos = (page - 1) * pagesize
    total_count = mongo.db[table].find(query).count()
    datacur = []
    if pagesize == 0:
        if sort is not None:
            datacur = mongo.db[table].find(query).sort(sort)
        else:
            datacur = mongo.db[table].find(query)
    else:
        if sort is not None:
            datacur = mongo.db[table].find(query).sort(sort).skip(pos).limit(pagesize)
        else:
            datacur = mongo.db[table].find(query).skip(pos).limit(pagesize)
    # datacur = mongo.db[table].find(query)
    # .sort([("survey_id", pymongo.ASCENDING), ("description", pymongo.DESCENDING)]).skip(pos).limit(pagesize)
    item_list = []
    for item in datacur:
        item.pop('_id')
        item_list.append(item)
    ret['code'] = 200
    ret['msg'] = '处理成功'
    ret['msg_flag'] = 'ok'
    ret['data'] = item_list
    ret['count'] = len(item_list)
    ret['total_count'] = total_count  # 总行数
    if pagesize == 0:
        ret['total_page'] = 1
    else:
        ret['total_page'] = math.ceil(total_count / pagesize)
    ret['page'] = page  # 当前第几页
    ret['pagesize'] = pagesize  # 每页大小
    return ret


def find_one(mongo, table, query):
    ret = deepcopy(g_ret)
    datacur = mongo.db[table].find_one(query)
    # datacur = mongo.db[table].find(query)
    # .sort([("survey_id", pymongo.ASCENDING), ("description", pymongo.DESCENDING)]).skip(pos).limit(pagesize)
    if datacur is None:
        item_list = []
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = item_list
        ret['count'] = 0
        ret['total_count'] = 0  # 总行数
        ret['total_page'] = 0
        ret['page'] = 0  # 当前第几页
        ret['pagesize'] = 1  # 每页大小
    else:
        item_list = []
        datacur.pop('_id')
        item_list.append(datacur)
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = item_list
        ret['count'] = len(item_list)
        ret['total_count'] = 1  # 总行数
        ret['total_page'] = 1
        ret['page'] = 1  # 当前第几页
        ret['pagesize'] = 1  # 每页大小
    return ret


def find_last(mongo, table, field):
    ret = deepcopy(g_ret)
    # ('surveys_collection').find({}).sort({'survey_id':-1}).limit(1)
    datacur = mongo.db[table].find({}).sort([(field, -1)]).limit(1)
    # datacur = mongo.db[table].find(query)
    # .sort([("survey_id", pymongo.ASCENDING), ("description", pymongo.DESCENDING)]).skip(pos).limit(pagesize)
    item = None
    for cur in datacur:
        item = cur
        break
    if item is None:
        item_list = []
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = item_list
        ret['count'] = 0
        ret['total_count'] = 0  # 总行数
        ret['total_page'] = 0
        ret['page'] = 0  # 当前第几页
        ret['pagesize'] = 1  # 每页大小
    else:
        item_list = []
        item.pop('_id')
        item_list.append(item)
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = item_list
        ret['count'] = len(item_list)
        ret['total_count'] = 1  # 总行数
        ret['total_page'] = 1
        ret['page'] = 1  # 当前第几页
        ret['pagesize'] = 1  # 每页大小
    return ret


def insert(mongo, table, docs):
    # RedisOper.set("nvshen号", "hao好")
    # print(RedisOper.get("nvshen号"))
    ret = deepcopy(g_ret)
    back = None
    try:
        back = mongo.db[table].insert(docs)
        if isinstance(back, list):
            ret['inserted_count'] = len(back)
        else:
            ret['inserted_count'] = 1
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
    except Exception as e:
        print(e)
        ret['inserted_count'] = -1
    finally:
        return ret


def update(mongo, table, query, setdoc, upsert=False):
    try:
        ret = deepcopy(g_ret)
        back = mongo.db[table].update_many(query, setdoc, upsert=upsert)
        ret['upserted_count'] = back.raw_result.get('n') - back.raw_result.get('nModified')
        ret['modified_count'] = back.raw_result.get('nModified')
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
    except Exception as e:
        print(e)
        ret['modified_count'] = -1
    finally:
        return ret


def delete(mongo, table, query):
    try:
        ret = deepcopy(g_ret)
        back = mongo.db[table].delete_many(query)
        ret['deleted_count'] = back.raw_result.get('n')
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
    except Exception as e:
        print(e)
        ret['deteted_count'] = -1
    finally:
        return ret


def aggregate(mongo, table, aggreatelist):
    # { $match: {company_id: 'canfu'}},
    # { $group: { _id: '$company_id', total: { $sum: '$price'} } }
    try:
        ret = deepcopy(g_ret)
        datacur = mongo.db[table].aggregate(aggreatelist)
        item_list = []
        for item in datacur:
            item_list.append(item)
        ret['code'] = 200
        ret['msg'] = '处理成功'
        ret['msg_flag'] = 'ok'
        ret['data'] = item_list
        ret['count'] = len(item_list)
        ret['total_count'] = len(item_list)  # 总行数
    except Exception as e:
        print(e)
    finally:
        return ret


def distinct(mongo, table, field, query={}):
    """
    分页查询 distinct
    :return:
    """
    ret = deepcopy(g_ret)
    datalist = mongo.db[table].find(query).distinct(field)
    # datacur = mongo.db[table].find(query)
    # .sort([("survey_id", pymongo.ASCENDING), ("description", pymongo.DESCENDING)]).skip(pos).limit(pagesize)
    item_list = []
    for item in datalist:
        item_list.append(item)
    ret['code'] = 200
    ret['msg'] = '处理成功'
    ret['msg_flag'] = 'ok'
    ret['data'] = item_list
    ret['count'] = len(item_list)
    ret['total_count'] = len(item_list)  # 总行数
    ret['total_page'] = 1
    ret['page'] = 1  # 当前第几页
    ret['pagesize'] = 1000  # 每页大小
    return ret


def distinct2field(mongo, table, field1, field2, query={}):
    """
    分页查询 distinct 多个字段
    :return:
    """
    ret = deepcopy(g_ret)
    field11 = '$' + field1
    field22 = '$' + field2
    datalist = mongo.db[table].aggregate([{'$group': {'_id': {field1: field11, field2: field22}}}])
    # datacur = mongo.db[table].find(query)
    # .sort([("survey_id", pymongo.ASCENDING), ("description", pymongo.DESCENDING)]).skip(pos).limit(pagesize)
    item_list = []
    for item in datalist:
        item_list.append(item.get('_id'))
    ret['code'] = 200
    ret['msg'] = '处理成功'
    ret['msg_flag'] = 'ok'
    ret['data'] = item_list
    ret['count'] = len(item_list)
    ret['total_count'] = len(item_list)  # 总行数
    ret['total_page'] = 1
    ret['page'] = 1  # 当前第几页
    ret['pagesize'] = 1000  # 每页大小
    return ret
# def insert_one(table, docs):
#     ret = deepcopy(g_ret)
#     back = mongo.db[table].insert_one(docs)
#     return ret
#
#
# def update_one(table, docs, query, upsert=False):
#     ret = deepcopy(g_ret)
#     back = mongo.db[table].update_one(docs, query, upsert=upsert)
#     return ret
#
#
# def delete_one(table, query):
#     ret = deepcopy(g_ret)
#     back = mongo.db[table].delete_one(query)
#     return ret

#
# rows = pagequery(settings.mongo, table='questions_collection', query={}, page=1, pagesize=110)
# print(rows)
